import React from 'react';
import {connect} from 'dva/index';
import {Button, Checkbox, Form, message, Modal, Popconfirm, Tabs} from 'antd';
import OrderEssentialInfo from './orderEssentialInfo';
import DeliveryReceiptInfo from './deliveryReceiptInfo';
import OrderTrailerInfo from './orderTrailerInfo';
import OrderDeclareInfo from './orderDeclareInfo';
import OrderSupplementInfo from './orderSupplementInfo';
import OrderCostInfo from './orderCostInfo';
import { fileUpload, download } from '../../utils/commons';
import Constants from '../../utils/Constants';

const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const CheckboxGroup = Checkbox.Group;
const R = require("ramda");

const labelStyle = {
    lineHeight: 2.5,
    borderTop: '1px solid #d9d9d9',
    borderBottom: '1px solid #d9d9d9',
    borderLeft: '1px solid #d9d9d9',
    width: 50,
    textAlign: 'center'
}

const orderDetail = Form.create()(class orderDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            orderId: null,
            receiptId: null,
            disabled: false,
            cstEdit: null,          //cstEdit为true时,客户信息模块disabled按props里的传递;为false时，通过cstInfoDisabled再判断disabled
            cstInfoDisabled: null,
            tabActiveKey: "1",
            businessApproval: true,    //限制业务员可见订单部分      
            businessOrder: true        //区分业务员审核或查看订单
        }
    }

    handleOpen = (receiptId, orderId, disabled, cstEdit, cstInfoDisabled, businessApproval, businessOrder) => {
        this.setState({ open: true, receiptId, orderId, disabled, cstEdit, cstInfoDisabled, businessApproval, businessOrder });
    }

    handleCancel = () => {
        this.keyList = [];
        this.setState({ open: false, tabActiveKey: "1" });
        this.props.form.resetFields();
        //if (this.props.refreshList) this.props.refreshList();
    }

    exportDelivery = () =>{
        let id = R.isNil(this.props.order.deliveryReceipt.id) ? "" : this.props.order.deliveryReceipt.id;
        let url = apiPath.mc + "/api/file/export/delivery/" + id;
        let conditions = null;
        download(url, conditions);
    }

    handleApproval = () => {
        let costForm = this.orderCostInfo.checkOrderCostInfo();
        costForm.id = this.state.orderId;
        if (!(R.isNil(costForm) || R.isEmpty(costForm))) {
            this.props.dispatch({
                type: 'order/approvalCharge',
                payload: {
                    ...costForm,
                    onSuccess: () => { this.handleCancel() }
                }
            })
        }
    }

    // keyList = ["1"];
    handleChangeTabe = (key) => {
        this.setState({ tabActiveKey: key })
        //this.keyList.push( key );
    }

    handleRefresh = () =>{
        this.props.dispatch({
            type: 'order/getById',
            payload: {
                receiptId: this.state.receiptId
            }
        }); 
    }

    handleMain = (status) => {
        let essForm = this.orderEssentialInfo.checkOrderEssentialInfo();
        essForm.soUrl = this.orderEssentialInfo.refs.soUrl.getUrl();

        if (!(R.isNil(essForm) || R.isEmpty(essForm))) {
            this.props.dispatch({
                type: 'order/updateOrderMain',
                payload: {
                    ...essForm,
                    id: this.state.orderId,
                    status: status,
                    bookingStatus: status,
                    onSuccess: (id) => { 
                        if (!this.orderEssentialInfo.refs.soUrl.getUrl() && this.orderEssentialInfo.refs.soUrl.getFiles().length > 0) {
                            fileUpload({
                                id,
                                modules: Constants.BOOKING_MODULES[0],
                                data: this.orderEssentialInfo.refs.soUrl.getFiles(),
                                onFail: this.handleCancel
                            });
                        }
                        this.handleRefresh() 
                    }
                }
            });
        }
    }

    handleTrailer = (status) => {
        let traForm = this.orderTrailerInfo.checkOrderTrailerInfo();
        if (!(R.isNil(traForm) || R.isEmpty(traForm))) {
            if(status == "2" && (["2", "4"].includes(this.props.order.deliveryReceipt.shipping) || ["1", "2", "3"].includes(this.props.order.deliveryReceipt.airFreight))){
                if(R.isNil(traForm.detailAddress) || R.isNil(traForm.loadingContacts) || R.isNil(traForm.loadingTelephone) || R.isNil(traForm.loadingTime) || R.isNil(traForm.unloadCompany) || R.isNil(traForm.unloadContacts) || R.isNil(traForm.unloadTelephone)
                    || R.isNil(traForm.unloadAddress) || R.isNil(traForm.productName) || R.isNil(traForm.probablyWeight) || R.isNil(traForm.probablyPackagesNum) || R.isNil(traForm.probablyCube) || R.isNil(traForm.pickUpCharge)){
                        message.error("请将必填项填写完整后提交");
                        return;
                }
            }

            if (this.props.order.odTrailer.status === "2") {
                if (["1", "3"].includes(this.props.order.deliveryReceipt.shipping)) {
                    traForm.weighBillUrlUrl = this.orderTrailerInfo.refs.weighBillUrlUrl.getUrl();
                    traForm.headstockPicUrl = this.orderTrailerInfo.refs.headstockPicUrl.getUrl();
                    traForm.tailstockPicUrl = this.orderTrailerInfo.refs.tailstockPicUrl.getUrl();
                    traForm.gpsUrl = this.orderTrailerInfo.refs.gpsUrl.getUrl();
                    traForm.alsoCabinetBillUrl = this.orderTrailerInfo.refs.alsoCabinetBillUrl.getUrl();
                    traForm.sendCarUrl = this.orderTrailerInfo.refs.sendCarUrl.getUrl();
                    traForm.otherUrl = this.orderTrailerInfo.refs.otherUrl.getUrl();
                    
                    if (this.orderTrailerInfo.refs.weighBillUrlUrl.getFiles().length === 0) {
                        message.error("必须上传过磅单凭证！");
                        return;
                    }
                    if (this.orderTrailerInfo.refs.headstockPicUrl.getFiles().length === 0) {
                        message.error("必须上传车头照凭证！");
                        return;
                    }
                    if (this.orderTrailerInfo.refs.tailstockPicUrl.getFiles().length === 0) {
                        message.error("必须上传车尾照凭证！");
                        return;
                    }
                    if (this.orderTrailerInfo.refs.gpsUrl.getFiles().length === 0) {
                        message.error("必须上传GPS定位凭证！");
                        return;
                    }
                    if (this.orderTrailerInfo.refs.alsoCabinetBillUrl.getFiles().length === 0) {
                        message.error("必须上传还柜纸凭证！");
                        return;
                    }
                    if (this.orderTrailerInfo.refs.sendCarUrl.getFiles().length === 0) {
                        message.error("必须上传派车单凭证！");
                        return;
                    }
                }

                if (["2", "4"].includes(this.props.order.deliveryReceipt.shipping) || ["1", "2", "3"].includes(this.props.order.deliveryReceipt.airFreight)) {
                    traForm.signedReceiptUrl = this.orderTrailerInfo.refs.signedReceiptUrl.getUrl();
                    if (this.orderTrailerInfo.refs.signedReceiptUrl.getFiles().length === 0) {
                        message.error("必须上传签收单凭证！");
                        return;
                    }
                }
            }

            this.props.dispatch({
                type: 'order/updateOrderTrailer',
                payload: {
                    ...traForm,
                    id: this.props.order.odTrailer && this.props.order.odTrailer ? this.props.order.odTrailer.id : null,
                    status: this.props.order.odTrailer.status == "2" ? "3" : status,
                    onSuccess: (id) => {
                        if ((this.props.order.odTrailer.status === "2")) {
                            if (["1", "3"].includes(this.props.order.deliveryReceipt.shipping)) {
                                if (!this.orderTrailerInfo.refs.weighBillUrlUrl.getUrl() && this.orderTrailerInfo.refs.weighBillUrlUrl.getFiles().length > 0) {     //此判断的意思是，附件更换过，从无到有或者从A到B
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[0],
                                        data: this.orderTrailerInfo.refs.weighBillUrlUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.headstockPicUrl.getUrl() && this.orderTrailerInfo.refs.headstockPicUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[1],
                                        data: this.orderTrailerInfo.refs.headstockPicUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.tailstockPicUrl.getUrl() && this.orderTrailerInfo.refs.tailstockPicUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[2],
                                        data: this.orderTrailerInfo.refs.tailstockPicUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.gpsUrl.getUrl() && this.orderTrailerInfo.refs.gpsUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[3],
                                        data: this.orderTrailerInfo.refs.gpsUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.alsoCabinetBillUrl.getUrl() && this.orderTrailerInfo.refs.alsoCabinetBillUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[4],
                                        data: this.orderTrailerInfo.refs.alsoCabinetBillUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.sendCarUrl.getUrl() && this.orderTrailerInfo.refs.sendCarUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[5],
                                        data: this.orderTrailerInfo.refs.sendCarUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                                if (!this.orderTrailerInfo.refs.otherUrl.getUrl() && this.orderTrailerInfo.refs.otherUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[6],
                                        data: this.orderTrailerInfo.refs.otherUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                            }

                            if (["2", "4"].includes(this.props.order.deliveryReceipt.shipping) || ["1", "2", "3"].includes(this.props.order.deliveryReceipt.airFreight)) {
                                if (!this.orderTrailerInfo.refs.signedReceiptUrl.getUrl() && this.orderTrailerInfo.refs.signedReceiptUrl.getFiles().length > 0) {
                                    fileUpload({
                                        id,
                                        modules: Constants.ORDERTRA_MODULES[7],
                                        data: this.orderTrailerInfo.refs.signedReceiptUrl.getFiles(),
                                        onFail: this.handleCancel
                                    });
                                }
                            }
                        }
                        this.handleRefresh()
                    }
                }
            });
        }
    }

    handleDeclare = (status) => {
        let decForm = this.orderDeclareInfo.checkOrderDeclareInfo();
        if (!(R.isNil(decForm) || R.isEmpty(decForm))) {
            if(status == "2"){
                if(!decForm.normalDeclareList && !decForm.payDeclareList){
                        message.error("正常单报关或买单报关至少填写其一的详细数据");
                        return;
                }
                if(decForm.normalDeclareList){
                    if(R.isEmpty(decForm.normalDeclareFee)){
                        message.error("请输入正常单报关费");
                        return;
                    }
                }
                if(decForm.payDeclareList){
                    if(R.isEmpty(decForm.payBillDeclareFee)){
                        message.error("请输入买单报关费");
                        return;
                    }
                }
            }

            if (this.props.order.odDeclare.status === "2") {
                decForm.declareBillUrl = this.orderDeclareInfo.refs.declareBillUrl.getUrl();
                decForm.passNoticeUrl = this.orderDeclareInfo.refs.passNoticeUrl.getUrl();
                decForm.otherUrl = this.orderDeclareInfo.refs.otherUrl.getUrl();

                if (this.orderDeclareInfo.refs.declareBillUrl.getFiles().length === 0) {
                    message.error("必须上传报关底单凭证！");
                    return;
                }
                if (this.orderDeclareInfo.refs.passNoticeUrl.getFiles().length === 0) {
                    message.error("必须上传放行通知书凭证！");
                    return;
                }
            }
            this.props.dispatch({
                type: 'order/updateOrderDeclare',
                payload: {
                    ...decForm,
                    id: this.props.order.odDeclare && this.props.order.odDeclare ? this.props.order.odDeclare.id : null,
                    status: this.props.order.odDeclare.status == "2" ? "3" : status,
                    onSuccess: (id) => {
                        if ((this.props.order.odDeclare.status === "2")) {
                            if (!this.orderDeclareInfo.refs.declareBillUrl.getUrl() && this.orderDeclareInfo.refs.declareBillUrl.getFiles().length > 0) {
                                fileUpload({
                                    id,
                                    modules: Constants.ORDERDEC_MODULES[0],
                                    data: this.orderDeclareInfo.refs.declareBillUrl.getFiles(),
                                    onFail: this.handleCancel
                                });
                            }
                            if (!this.orderDeclareInfo.refs.passNoticeUrl.getUrl() && this.orderDeclareInfo.refs.passNoticeUrl.getFiles().length > 0) {
                                fileUpload({
                                    id,
                                    modules: Constants.ORDERDEC_MODULES[1],
                                    data: this.orderDeclareInfo.refs.passNoticeUrl.getFiles(),
                                    onFail: this.handleCancel
                                });
                            }
                            if (!this.orderDeclareInfo.refs.otherUrl.getUrl() && this.orderDeclareInfo.refs.otherUrl.getFiles().length > 0) {
                                fileUpload({
                                    id,
                                    modules: Constants.ORDERDEC_MODULES[2],
                                    data: this.orderDeclareInfo.refs.otherUrl.getFiles(),
                                    onFail: this.handleCancel
                                });
                            }
                        } 
                        this.handleRefresh()
                    }
                }
            });
        }
    }

    handleSi = (status) => {
        let siForm = this.orderSupplementInfo.checkOrderSupplementInfo();
        if (!(R.isNil(siForm) || R.isEmpty(siForm))) {
            if (this.props.order.odSi.status === "2") {
                siForm.ladingBillUrl = this.orderSupplementInfo.refs.ladingBillUrl.getUrl();
                if (this.orderSupplementInfo.refs.ladingBillUrl.getFiles().length === 0) {
                    message.error("必须上传提单确认件凭证！");
                    return;
                }
            }
           
            //siForm.siUrl = this.orderSupplementInfo.refs.siUrl.getUrl();
            this.props.dispatch({
                type: 'order/updateOrderSi',
                payload: {
                    ...siForm,
                    id: this.props.order.odSi && this.props.order.odSi ? this.props.order.odSi.id : null,
                    status: this.props.order.odSi.status == "2" ? "3" : status,
                    onSuccess: (id) => {
                        if ((this.props.order.odSi.status === "2")) {
                            if (!this.orderSupplementInfo.refs.ladingBillUrl.getUrl() && this.orderSupplementInfo.refs.ladingBillUrl.getFiles().length > 0) {
                                fileUpload({
                                    id,
                                    modules: Constants.ORDERSI_MODULES[0],
                                    data: this.orderSupplementInfo.refs.ladingBillUrl.getFiles(),
                                    onFail: this.handleCancel
                                });
                            }
                        }
                        // if (!this.orderSupplementInfo.refs.siUrl.getUrl() && this.orderSupplementInfo.refs.siUrl.getFiles().length > 0) {
                        //     fileUpload({
                        //         id,
                        //         modules: Constants.ORDERSI_MODULES[1],
                        //         data: this.orderSupplementInfo.refs.siUrl.getFiles(),
                        //         onFail: this.handleCancel
                        //     });
                        // }
                        this.handleRefresh()
                    }
                }
            });
        }
    }

    render() {
        let dataSource = this.props.order.dataSource ? this.props.order.dataSource : {};
        let deliveryReceiptData = this.props.order.deliveryReceipt ? this.props.order.deliveryReceipt : null;
        let portServiceItem = deliveryReceiptData.portService ? deliveryReceiptData.portService.split(",") : null;
        const { getFieldDecorator } = this.props.form;

        let footer = [
            <Button key="saveMain" size="large" loading={this.props.loading} onClick={this.handleMain.bind(this, "1")} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "1" && this.props.order.order.bookingStatus == "1" ? 'inline-block' : 'none') }}>保存主界面信息</Button>,
            <Button key="saveTra" size="large" loading={this.props.loading} onClick={this.handleTrailer.bind(this, "1")} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "3" && this.props.order.odTrailer.status == "1" ? 'inline-block' : 'none') }}>保存拖车信息</Button>,
            <Button key="saveDec" size="large" loading={this.props.loading} onClick={this.handleDeclare.bind(this, "1")} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "4" && this.props.order.odDeclare.status == "1" ? 'inline-block' : 'none') }}>保存报关信息</Button>,
            <Button key="saveSi" size="large" loading={this.props.loading} onClick={this.handleSi.bind(this, "1")} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "5" && this.props.order.odSi.status == "1" ? 'inline-block' : 'none') }}>保存补料信息</Button>,
            <Popconfirm placement="top" 
                        title={'数据提交后不可以重新编辑，是否确认提交？'} 
                        onConfirm={this.handleMain.bind(this, "2")}
                        okText="是" cancelText="否">
                        <Button key="subMain" size="large" loading={this.props.loading} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "1" && this.props.order.order.bookingStatus == "1" ? 'inline-block' : 'none') }}>提交主界面</Button>
            </Popconfirm>,
            <Popconfirm placement="top" 
                        title={'数据提交后不可以重新编辑，是否确认提交？'} 
                        onConfirm={this.handleTrailer.bind(this, "2")}
                        okText="是" cancelText="否">
                        <Button key="subTra" size="large" loading={this.props.loading} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "3" && (this.props.order.odTrailer.status == "1" || this.props.order.odTrailer.status == "2") ? 'inline-block' : 'none') }}>提交拖车</Button>
            </Popconfirm>,
            <Popconfirm placement="top" 
                        title={'数据提交后不可以重新编辑，是否确认提交？'} 
                        onConfirm={this.handleDeclare.bind(this, "2")}
                        okText="是" cancelText="否">
                        <Button key="subDec" size="large" loading={this.props.loading} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "4" && (this.props.order.odDeclare.status == "1" || this.props.order.odDeclare.status == "2") ? 'inline-block' : 'none') }}>提交报关</Button>
            </Popconfirm>,
            <Popconfirm placement="top" 
                        title={'数据提交后不可以重新编辑，是否确认提交？'} 
                        onConfirm={this.handleSi.bind(this, "2")}
                        okText="是" cancelText="否">
                        <Button key="subSi" size="large" loading={this.props.loading} style={{ display: this.state.disabled ? 'none' : (this.state.tabActiveKey == "5" && (this.props.order.odSi.status == "1" || this.props.order.odSi.status == "2") ? 'inline-block' : 'none') }}>提交补料</Button>
            </Popconfirm>,
            <Button key="export" size="large" loading={this.props.loading} onClick={this.exportDelivery.bind(this)} style={{ display: this.state.tabActiveKey == "2" ? 'inline-block' : 'none' }}>导出交接单</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>退出</Button>
        ];

        let approvalFooter = [
            <Button key="approval" size="large" loading={this.props.loading} onClick={this.handleApproval.bind(this, "2")} style={{ display: this.state.disabled || this.state.businessOrder ? 'none' : 'inline-block' }}>提交</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];

        return (
            <div>
                {this.state.open ?
                    <Modal maskClosable={false} visible={this.state.open}
                        width={930} title={"操作跟单"} confirmLoading={this.props.loading}
                        onCancel={this.handleCancel.bind(this)}
                        footer={this.state.businessApproval ? footer : approvalFooter}
                    >
                        <Tabs tabPosition={'top'} activeKey={this.state.tabActiveKey} onChange={this.handleChangeTabe.bind(this)}>
                            {this.state.businessApproval ?
                                <TabPane tab="主界面" key="1">
                                    <OrderEssentialInfo wrappedComponentRef={(inst) => this.orderEssentialInfo = inst} disabled={this.state.disabled} dataSource={undefined} />
                                </TabPane>
                                : ""}

                            <TabPane tab="交接单" key={this.state.businessApproval ? "2" : "1"}>
                                <DeliveryReceiptInfo wrappedComponentRef={(inst) => this.deliveryReceiptInfo = inst} disabled={!this.state.disabled} dataSource={undefined} isOrder={true} cstEdit={this.state.cstEdit} cstInfoDisabled={this.state.cstInfoDisabled} businessOrder={this.state.businessOrder} />
                            </TabPane>

                            {(portServiceItem && portServiceItem.includes("1")) && this.state.businessApproval ?
                                <TabPane tab="拖车" key="3">
                                    <OrderTrailerInfo wrappedComponentRef={(inst) => this.orderTrailerInfo = inst} disabled={this.state.disabled} dataSource={undefined} />
                                </TabPane>
                                : ""}

                            {(portServiceItem && portServiceItem.includes("2")) && this.state.businessApproval ?
                                <TabPane tab="报关" key="4">
                                    <OrderDeclareInfo wrappedComponentRef={(inst) => this.orderDeclareInfo = inst} disabled={this.state.disabled} dataSource={undefined} />
                                </TabPane>
                                : ""}

                            {this.state.businessApproval ?
                                <TabPane tab="补料" key="5">
                                    <OrderSupplementInfo wrappedComponentRef={(inst) => this.orderSupplementInfo = inst} disabled={this.state.disabled} dataSource={undefined} receiptId={this.state.receiptId} orderId={this.state.orderId} />
                                </TabPane>
                                : ""}

                            <TabPane tab="费用" key="6">
                                <OrderCostInfo  wrappedComponentRef={(inst) => this.orderCostInfo = inst} 
                                                disabled={this.state.disabled} 
                                                orderId={this.state.orderId} 
                                                receiptId={this.state.receiptId} 
                                                businessApproval={this.state.businessApproval} 
                                                businessOrder={this.state.businessOrder}  
                                                fetchDetail={this.props.fetchDetail}
                                />
                            </TabPane>
                        </Tabs>
                    </Modal>
                    : null}
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.order, order: state.order
    };
}

export default connect(mapStateToProps)(orderDetail);